package com.cnstrong.webview2

import android.content.Context
import android.util.AttributeSet
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView

class X5WebView : WebView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet)
    constructor(context: Context, attributeSet: AttributeSet?, style: Int = 0) : super(
        context,
        attributeSet,
        style
    )

    init {
        initWebViewSettings()
    }

    private val mHtmlHandlerMap = mutableMapOf<String, HtmlDataHandler>()

    private fun initWebViewSettings() {
        val webSetting = this.settings
        webSetting.javaScriptEnabled = true
        webSetting.javaScriptCanOpenWindowsAutomatically = true
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls = true
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(true)
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSetting.domStorageEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE

        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的设计
    }

    fun findHtmlDataReceiver(handlerName: String): HtmlDataHandler? {
        return mHtmlHandlerMap[handlerName]
    }

    fun registerHtmlHandler(
        handlerName: String,
        handler: HtmlDataHandler
    ): HtmlDataHandler? {
        val previous = findHtmlDataReceiver(handlerName)
        mHtmlHandlerMap[handlerName] = handler
        return previous
    }

    fun unRegisterHtmlHandler(handlerName: String) {
        mHtmlHandlerMap.remove(handlerName)
    }

    override fun destroy() {
        mHtmlHandlerMap.clear()
        super.destroy()
    }
}